﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using PmfWeb.Core.Utility;

namespace PmfWeb.Core.Data
{
    /// <summary>
    /// 数据访问基础类
    /// </summary>
    public abstract class SqlHelper
    {
        #region 数据库连接字符串
        private static string connectionString = string.Empty;
        private static readonly Rijndael_ rij = new Rijndael_();

        ///<summary>
        /// 设置当前数据库连接字符串
        ///</summary>
        public static string ConnString
        {
            get
            {
                if (connectionString == string.Empty)
                {
                    string str = ConfigurationManager.ConnectionStrings["connString2"].ToString();
                    //str = rij.Decrypt(str);  //解密连接字符串
                    return str;
                }
                return connectionString;
            }
            set
            {
                connectionString = value;
            }
        }
        #endregion

        #region 获取最大值
        public static int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ")+1 from " + TableName;
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            return int.Parse(obj.ToString());
        }
        #endregion

        #region 执行Sql语句(指定的时间内执行)
        public static int ExecuteSqlByTime(string SQLString, int Times)
        {
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
        #endregion

        #region 执行多条SQL语句，实现数据库事务。
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>		
        public static int ExecuteSqlTran(List<string> SQLStringList)
        {
            if (SQLStringList == null) throw new ArgumentNullException("SQLStringList");
            using (SqlConnection conn = new SqlConnection(ConnString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch
                {
                    tx.Rollback();
                    return 0;
                }
            }
        }

        #endregion

        #region 执行存储过程,返回多个结果集(返回DataSet)
        /// <summary>
        /// 返回多个结果集
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <returns>DataSet对象</returns>
        public static DataSet ExecuteProc(string procName)
        {
            using (SqlConnection conn = new SqlConnection(ConnString))
            {
                DataSet ds = new DataSet();
                try
                {
                    conn.Open();
                    SqlDataAdapter da = new SqlDataAdapter(procName, conn);
                    da.Fill(ds);
                    return ds;
                }
                catch
                {

                }
                finally
                {
                    conn.Close();
                }
            }
            return null;
        }
        #endregion

        #region 执行存储过程,返回多个结果集(返回SqlDataReader)
        /// <summary>
        /// 返回多个结果集
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <returns>DataSet对象</returns>
        public static SqlDataReader ExecuteMoreRecord_Proc(string procName)
        {
            using (SqlConnection conn = new SqlConnection(ConnString))
            {
                DataSet ds = new DataSet();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = conn;
                cmd.CommandText = procName;
                try
                {
                    conn.Open();
                    SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    return reader;
                }
                catch
                {

                }
                finally
                {
                    //conn.Close();
                }
            }
            return null;
        }
        #endregion

        #region 执行带一个存储过程参数的的SQL语句(返回受影响的记录数int值)
        /// <summary>
        /// 执行带一个存储过程参数的的SQL语句。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="content">参数内容,比如一个字段是格式复杂的文章，有特殊符号，可以通过这个方式添加</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, string content)
        {
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                SqlCommand cmd = new SqlCommand(SQLString, connection);
                System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
                myParameter.Value = content;
                cmd.Parameters.Add(myParameter);
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (SqlException e)
                {
                    throw e;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                }
            }
        }
        #endregion

        #region  执行一条计算查询结果语句，返回查询结果（object）。
        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public static object GetSingle(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        return obj;
                    }
                    catch (SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }



        /// <summary>
        /// 执行一个查询，返回单值
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="Times">超时时间</param>
        /// <returns>Object对象</returns>
        public static object GetSingle(string SQLString, int Times)
        {
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        return obj;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
        #endregion


        #region 数据库事务
        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public static void ExecuteSqlTran(Hashtable SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(ConnString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(ConnString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    SqlCommand cmd = new SqlCommand();
                    try
                    {
                        int indentity = 0;
                        //循环
                        foreach (DictionaryEntry myDE in SQLStringList)
                        {
                            string cmdText = myDE.Key.ToString();
                            SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
                            foreach (SqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.InputOutput)
                                {
                                    q.Value = indentity;
                                }
                            }
                            PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            foreach (SqlParameter q in cmdParms)
                            {
                                if (q.Direction == ParameterDirection.Output)
                                {
                                    indentity = Convert.ToInt32(q.Value);
                                }
                            }
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        throw;
                    }
                }
            }
        }

        #region 执行计算SQL语句
        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <param name="cmdParms"></param>
        /// <returns>查询结果（object）</returns>
        public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        return obj;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                }
            }
        }
        #endregion

        #region 返回SqlDataReader对象
        /// <summary>
        /// 执行查询语句，返回SqlDataReader (注意,调用该方法后，一定要对SqlDataReader进行Close)
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)
        {
            SqlConnection connection = new SqlConnection(ConnString);
            SqlCommand cmd = new SqlCommand();
            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (SqlException e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 执行查询语句，返回SqlDataReader ( 注意：调用该方法后，一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string SQLString)
        {
            SqlConnection connection = new SqlConnection(ConnString);
            SqlCommand cmd = new SqlCommand();
            try
            {
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 执行多条sql语句
        /// </summary>
        /// <param name="strSqls">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(List<string> strSqls)
        {
            StringBuilder sqls = new StringBuilder();
            for (int i = 0; i < strSqls.Count; i++)
            {
                sqls.Append(strSqls.ToString());
                sqls.Append(";");
            }

            SqlConnection connection = new SqlConnection(ConnString);
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sqls.ToString();
                cmd.Connection = connection;
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
        }
        #endregion

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <param name="cmdParms"></param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                SqlCommand cmd = new SqlCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (SqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="conn"></param>
        /// <param name="trans"></param>
        /// <param name="cmdText"></param>
        /// <param name="cmdParms"></param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (SqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }
        #endregion

        #region 存储过程操作
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <returns>SqlDataReader</returns>
        public static DataSet RunProcedure(string storedProcName)
        {
            DataSet dataSet;
            SqlDataAdapter da;
            SqlCommand cmd;
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                dataSet = new DataSet();
                connection.Open();
                da = new SqlDataAdapter();
                cmd = new SqlCommand();

                da.SelectCommand = cmd;
                da.SelectCommand.Connection = connection;
                da.SelectCommand.CommandText = storedProcName;
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                da.Fill(dataSet);
            }
            return dataSet;
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="Parameters">存储过程参数</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader RunProcedure(string storedProcName, SqlParameter[] Parameters)
        {
            SqlConnection connection = new SqlConnection(ConnString);
            SqlDataReader returnReader;
            connection.Open();
            SqlCommand command = BuildQueryCommand(connection, storedProcName, Parameters);
            command.CommandType = CommandType.StoredProcedure;
            returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
            return returnReader;
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="Parameters">存储过程参数</param>
        /// <param name="results">接收返回值</param>
        /// <returns>DataSet</returns>
        public static DataTable RunProc(string storedProcName, SqlParameter[] Parameters, out string[] results)
        {
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, Parameters);
                sqlDA.Fill(dataSet);
                connection.Close();
                int counter = 0;
                results = new string[] {};
                for (int i = 0,j = Parameters.Length; i < j; i++)
                {
                    SqlParameter para = Parameters[i];
                    if (ParameterDirection.Output == para.Direction || ParameterDirection.InputOutput == para.Direction)
                    {
                        results[counter++] = para.Value.ToString();
                    }
                }
                return dataSet.Tables[0];
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="Parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] Parameters, string tableName)
        {
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, Parameters);
                sqlDA.Fill(dataSet, tableName);
                connection.Close();
                

                return dataSet;
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="Parameters">存储过程参数</param>
        /// <returns>DataSet</returns>
        public static DataSet GetDataSet(string storedProcName, SqlParameter[] Parameters, out string[] results)
        {
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, Parameters);
                sqlDA.Fill(dataSet);
                connection.Close();
                int counter = 0;
                results = new string[] { };
                for (int i = 0, j = Parameters.Length; i < j; i++)
                {
                    SqlParameter para = Parameters[i];
                    if (ParameterDirection.Output == para.Direction || ParameterDirection.InputOutput == para.Direction)
                    {
                        results[counter++] = para.Value.ToString();
                    }
                }
                return dataSet;
            }
        }
        /// <summary>
        /// 执行存储过程(指定时间内),指定返回值DataSet里的表名
        /// </summary>
        /// <param name="storedProcName"></param>
        /// <param name="Parameters"></param>
        /// <param name="tableName"></param>
        /// <param name="Times"></param>
        /// <returns></returns>
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] Parameters, string tableName, int Times)
        {
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, Parameters);
                sqlDA.SelectCommand.CommandTimeout = Times;
                sqlDA.Fill(dataSet, tableName);
                connection.Close();
                return dataSet;
            }
        }


        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="Parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] Parameters)
        {
            SqlCommand command = new SqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter parameter in Parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }
            return command;
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="procName">存储过程名称</param>
        /// <param name="paras"></param>
        public static string GetProcSingle(string procName, SqlParameter[] paras)
        {
            StringBuilder result = new StringBuilder();
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                try
                {
                    connection.Open();
                    using (SqlCommand cmd = BuildQueryCommand(connection, procName, paras))
                    {
                        cmd.ExecuteNonQuery();
                        foreach (IDataParameter parameter in paras)
                        {
                            if (parameter.Direction == ParameterDirection.Output)
                            {
                                result.Append(parameter.Value);
                                result.Append(",");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    connection.Close();
                    connection.Dispose();
                    throw;
                }
            }

            if (0 < result.ToString().Length)
            {
                string str = "";
                str = result.ToString().Remove(result.ToString().Length - 1); //过滤掉最后一位逗号
                if (string.IsNullOrEmpty(str))
                {
                    return "0";
                }
                return str;
            }
            return "0";
        }
        /// <summary>
        /// 执行存储过程，返回影响的行数		
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="Parameters">存储过程参数</param>
        /// <param name="iRows">影响的行数</param>
        /// <returns></returns>
        public static int RunProcedure(string storedProcName, IDataParameter[] Parameters, out int iRows)
        {
            using (SqlConnection connection = new SqlConnection(ConnString))
            {
                connection.Open();
                using (SqlCommand command = BuildIntCommand(connection, storedProcName, Parameters))
                {
                    iRows = command.ExecuteNonQuery();
                    int result = (int)command.Parameters["ReturnValue"].Value;
                    //Connection.Close();
                    return result;
                }
            }
        }

        /// <summary>
        /// 创建SqlCommand 对象实例(用来返回一个整数值)	
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="Parameters">存储过程参数</param>
        /// <returns>SqlCommand 对象实例</returns>
        private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] Parameters)
        {
            SqlCommand command = BuildQueryCommand(connection, storedProcName, Parameters);
            command.Parameters.Add(new SqlParameter("ReturnValue",
                SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));
            return command;
        }
        #endregion

        #region 大量数据迁移(比如大量插入,修改)
        /// <summary>
        /// 大批量数据迁移()
        /// </summary>
        /// <param name="connSrc">源数据库连接字符串</param>
        /// <param name="connTarget">目标数据库连接字符串</param>
        /// <param name="ProcName">存储过程名(要迁移的数据)</param>
        /// <param name="T_tableName">要迁移到的目标数据库的表名</param>
        public static void BulkDataTransfer(string connSrc, string connTarget, string ProcName, string T_tableName)
        {
            SqlConnection connectionSrc = new SqlConnection(connSrc);  //源数据连接对象
            SqlCommand myCommand = new SqlCommand();
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.Connection = connectionSrc;
            myCommand.CommandText = ProcName;
            connectionSrc.Open();
            SqlDataReader dr = myCommand.ExecuteReader();

            //目标数据连接对象
            SqlConnection connectionTarget = new SqlConnection(connTarget);
            connectionTarget.Open();

            //大数据复制对象
            SqlBulkCopy bulk = new SqlBulkCopy(connectionTarget);
            bulk.DestinationTableName = T_tableName;  //要迁移到的目标数据库的表名
            try
            {
                if (dr != null) bulk.WriteToServer(dr);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                connectionTarget.Close();
                if (dr != null) dr.Close();
                connectionSrc.Close();
                bulk.Close();
            }
        }
        #endregion

    }

}
